import axios, { AxiosError } from 'axios'
import { getProfile, removeProfile } from '@/utils/storage'
// import useStore from '@/store'
import { ElMessage } from 'element-plus'
import router from '@/router'

export const baseURL = 'https://apipc-xiaotuxian-front.itheima.net/'
const instance = axios.create({
  // 备用地址
  // http://pcapi-xiaotuxian-front.itheima.net/
  // http://pcapi-xiaotuxian-front-devtest.itheima.net/
  
  // baseURL: 'https://apipc-xiaotuxian-front.itheima.net/',
  baseURL,
  timeout: 5000
})



// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    // return config

    const profile = getProfile()
    if (profile.token) {
      config.headers!.Authorization = `Bearer ${profile.token}`
    }

    return config
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response
  },
  function (error: AxiosError<{ message: string }>) {
    // 对响应错误做点什么
    // return Promise.reject(error)

    console.log('---axios error---', error);

    if (error.response?.status === 401) {
      ElMessage.error('登录超时!')

      // 清除profile
      removeProfile()

      const redirectUrl = encodeURIComponent(router.currentRoute.value.fullPath)
      router.push(`/login?redirectUrl=${redirectUrl}`)
    }
   // 对响应错误做点什么
   return Promise.reject(error)
  }
)


export default instance